<template>
  <div>
    <!--页面区域-->
    <div class="page-view">
      <a-space align="start">
        <!-- <a-tabs animated activeKey="0" tab-position="left" :style="{ height: '75vh' }" @tabClick="tabClick">
          <a-tab-pane v-for="(item, index) in serviceData.chatList" :key="index" :tab="item.username">
          </a-tab-pane>
        </a-tabs> -->
        <div style="margin-right: 20px;height: 75vh;width: 200px;">
          <a-list size="small" :data-source="serviceData.chatList">
            <template #renderItem="{ item, index }">
              <a-list-item class="chat-item" :class="item.id == serviceData.caht.id ? 'chat-item-selected' : ''"
                @click="tabClick(index)">
                {{ item.username }}
              </a-list-item>
            </template>
          </a-list>
        </div>
        <a-divider type="vertical" style="height: 75vh;" />
        <a-card v-if="serviceData.visible" :title="serviceData.caht.username" class="service-card"
          :body-style="{ padding: '10px 0px' }" :headStyle="{ backgroundColor: '#1890ff', color: '#fff' }">
          <template #extra>
            <a-space size="middle">
              <a @click="closeService()" style="color: #fff;">关闭</a>
            </a-space>
          </template>
          <div class="service-list">
            <p v-for="(item, index) in serviceData.list" :key="index">
              <a-space :class="item.senderId == userStore.admin_user_id ? 'right' : 'left'">
                <img class="service-avatar" :src="AvatarIcon">
                <div class="service-msg">
                  <template v-if="item.sendType == '2'">
                    <img class="service-thing" :src="item.sendContent.cover" />
                    <span>{{ item.sendContent.title }}</span>
                  </template>
                  <span v-else>{{ item.sendContent }}</span>
                </div>
              </a-space>
            </p>
          </div>
          <template #actions>
            <a-space>
              <a-input style="width: 400px" placeholder="请输入" v-model:value="serviceData.input" @pressEnter="sendMsg">
              </a-input>
              <a-button type="primary" @click="sendMsg">发送</a-button>
            </a-space>
          </template>
        </a-card>
        <a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" description="请选择一个会话" />
      </a-space>
    </div>
  </div>
</template>

<script setup lang="ts">
import AvatarIcon from '/@/assets/images/avatar.jpg';
import { message } from 'ant-design-vue';
import { openChatApi, sendMessageApi, allMessageApi, newMessageApi, chatListApi } from '/@/api/chat'
import { useUserStore } from "/@/store";
import { Empty } from 'ant-design-vue';

const userStore = useUserStore();

const serviceData = reactive({
  caht: <any>{},
  chatList: <any>[],
  list: <any>[],
  input: '',
  visible: false,
  isGet: false,
  timer: <any>undefined,
});

onMounted(() => {
  getDataList();
});
onUnmounted(() => {
  clearInterval(serviceData.timer);
});

const closeService = () => {
  serviceData.list = [];
  serviceData.visible = false;
  clearInterval(serviceData.timer);
}
const openService = async () => {
  if (serviceData.visible) {
    closeService();
  }
  let reqData = {
    userId: serviceData.caht.userId,
    businessId: userStore.admin_user_id,
  };
  await openChatApi(reqData);
  const resp = await allMessageApi(reqData);
  unshiftMsg(resp.data);
  timerMessage();
  serviceData.visible = true;
}
const unshiftMsg = (list) => {
  list.forEach(element => {
    if (element.sendType == '2') {
      element.sendContent = JSON.parse(element.sendContent);
    }
    serviceData.list.unshift(element);
  });
}
const sendMsg = async () => {
  let input = serviceData.input;
  if (input === null || input === undefined || input === '') {
    return;
  }
  let data = {
    userId: serviceData.caht.userId,
    businessId: userStore.admin_user_id,
    senderId: userStore.admin_user_id,
    sendType: '1',
    sendContent: input,
  }
  await sendMessageApi(data);
  serviceData.input = '';
  getNewMessage();
}
const timerMessage = () => {
  serviceData.timer = setInterval(() => {
    getNewMessage()
  }, 1500);
}
const getNewMessage = () => {
  if (serviceData.isGet) {
    return;
  }
  serviceData.isGet = true;
  let data = {
    userId: serviceData.caht.userId,
    businessId: userStore.admin_user_id,
    messageId: <any>undefined,
  }
  let msg = serviceData.list[0];
  data.messageId = msg ? msg.id : '';
  newMessageApi(data).then(resp => {
    unshiftMsg(resp.data);
    serviceData.isGet = false;
  }).catch(err => {
    serviceData.isGet = false;
  })
}

const onSearch = () => {
  console.log('onSearch')
}
const tabClick = (value) => {
  serviceData.caht = serviceData.chatList[value];
  openService();
}
const getDataList = () => {
  chatListApi({
    businessId: userStore.admin_user_id,
  }).then((res) => {
    serviceData.chatList = res.data;
  })
    .catch((err) => {
      message.error(err.msg || '查询失败');
    });
};
</script>

<style scoped lang="less">
.page-view {
  min-height: 100%;
  background: #fff;
  padding: 24px;
  display: flex;
  flex-direction: column;
}

.table-operations {
  margin-bottom: 16px;
  text-align: right;
}

.table-operations>button {
  margin-right: 8px;
}

.service-list(webkit-scrollbar) {
  display: none;
}

.service-card {
  width: 500px;
  background-color: #f5f5f5;
  border-radius: 10px;
}

.service-list {
  height: 60vh;
  overflow: auto;
  display: flex;
  flex-direction: column-reverse;

  .left {
    width: 100%;
    padding: 0px 10px;
    display: flex;
    flex-direction: row
  }

  .right {
    width: 100%;
    padding: 0px 10px;
    display: flex;
    flex-direction: row-reverse
  }
}

.service-avatar {
  width: 30px;
  height: 30px;
}

.service-thing {
  height: 60px;
  object-fit: contain;
  border-radius: 6px;
}

.service-msg {
  max-width: 400px;
  word-wrap: break-word;
  overflow-wrap: break-word;
  word-break: keep-all;
  padding: 4px;
  background-color: #fff;
  min-height: 40px;
  border-radius: 16px;
  padding-left: 10px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
}

.chat-item {
  width: 100%;
  height: 40px;
  display: flex;
  justify-content: center;
  cursor: pointer;

  &:hover {
    color: #1890ff;
    background-color: #e6f7ff;
  }
}

.chat-item-selected {
  color: #1890ff;
  background-color: #e6f7ff;
  position: relative;

  &:after {
    content: '';
    width: 1px;
    height: 40px;
    background-color: #1890ff;
    position: absolute;
    right: 0;
    top: 0;
  }
}
</style>
